<template>
  <div class="bikes-container">
    <div style="margin-bottom: 20px; margin-top: -20px;">
      <el-button type="primary" @click="dialogFormVisible = true">增加订单</el-button>
      <!-- <el-input v-model="Bikenumber" placeholder="单车编号" style="width: 163px; margin-left: 12px;"></el-input>
      <el-select v-model="status" style="width: 163px; margin-left: 12px;" placeholder="单车状态">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-button type="primary" style="margin-left: 12px;" @click="load">搜索</el-button>
      <el-button type="primary" style="margin-left: 12px;" @click="reset">重置</el-button> -->
    </div>
    <el-card>
      <el-table :data="orderTableData" style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column header-align="center" align="center" prop="orderid" label="ID"></el-table-column>
        <el-table-column prop="bikeid" label="单车编号" header-align="center" align="center" />
        <el-table-column prop="userid" label="用户ID" header-align="center" align="center" />
        <el-table-column prop="starttime" label="订单开始时间" header-align="center" align="center" />
        <el-table-column prop="endtime" label="订单结束时间" header-align="center" align="center" />
        <el-table-column prop="startlatitude" label="起点经纬度" header-align="center" align="center">
          <template #default="scope">
            <el-tag>[{{ scope.row.startlatitude }}, {{ scope.row.startlongitude }}]</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="endlatitude" label="终点经纬度" header-align="center" align="center">
          <template #default="scope">
            <el-tag>[{{ scope.row.endlatitude }}, {{ scope.row.endlongitude }}]</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="distance" label="骑行距离(km)" header-align="center" align="center" />
        <el-table-column prop="createdat" label="生成订单时间" header-align="center" align="center" />
        <el-table-column prop="note" label="备注" header-align="center" align="center" />
        <el-table-column label="Operation" header-align="center" align="center">
          <template #default="scope">
            <el-button type="text" size="small" plain @click="updateOrder(scope.row)">编辑</el-button>
            <el-button type="text" size="small" plain @click="deleteOrder(scope.row.orderid)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination @current-change="handleCurrentChange" :current-page="pageNum" :page-size="pageSize" layout="total, prev, pager, next" :total="total"></el-pagination>
      </div>
    </el-card>

    <el-dialog title="增加订单" v-model="dialogFormVisible">
      <el-form ref="BikeForm" :model="addOrderBike" label-width="80px">
        <el-form-item label="单车编号">
          <el-select v-model="addOrderBike.bikeid" placeholder="请选择单车编号" style="width: 220px;">
            <el-option v-for="bike in bikeOptions" :key="bike.value" :label="bike.label" :value="bike.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-select v-model="addOrderBike.userid" placeholder="请选择用户ID" style="width: 220px;">
            <el-option v-for="user in userOptions" :key="user.value" :label="user.label" :value="user.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker type="datetime" v-model="addOrderBike.starttime" placeholder="请选择选择订单开始时间" value-format="YYYY-MM-DD HH:mm:ss" @change="selectChange" />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker type="datetime" v-model="addOrderBike.endtime" placeholder="请选择选择订单结束时间" value-format="YYYY-MM-DD HH:mm:ss" @change="selectChange" />
        </el-form-item>
        <el-form-item label="起点经度">
          <el-input v-model="addOrderBike.startlatitude" placeholder="请输入起点经度" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="起点纬度">
          <el-input v-model="addOrderBike.startlongitude" placeholder="请输入起点纬度" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="终点经度">
          <el-input v-model="addOrderBike.endlatitude" placeholder="请输入终点经度" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="终点纬度">
          <el-input v-model="addOrderBike.endlongitude" placeholder="请输入终点纬度" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="骑行距离">
          <el-input v-model="addOrderBike.distance" placeholder="请输入骑行距离" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="生成时间">
          <el-date-picker type="datetime" v-model="addOrderBike.createdat" placeholder="请选择选择订单生成时间" value-format="YYYY-MM-DD HH:mm:ss" @change="selectChange" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addBikeOrder">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="更新单车" v-model="dialogUpdateVisible">
      <el-form ref="BikeForm" :model="updateOrderForm" label-width="80px">
        <el-form-item label="单车编号">
          <el-select v-model="updateOrderForm.bikeid" placeholder="请选择单车编号" style="width: 220px;">
            <el-option v-for="bike in bikeOptions" :key="bike.value" :label="bike.label" :value="bike.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-select v-model="updateOrderForm.userid" placeholder="请选择用户ID" style="width: 220px;">
            <el-option v-for="user in userOptions" :key="user.value" :label="user.label" :value="user.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker type="datetime" v-model="updateOrderForm.starttime" placeholder="请选择选择订单开始时间" value-format="YYYY-MM-DD HH:mm:ss" @change="selectChange" />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker type="datetime" v-model="updateOrderForm.endtime" placeholder="请选择选择订单结束时间" value-format="YYYY-MM-DD HH:mm:ss" @change="selectChange" />
        </el-form-item>
        <el-form-item label="起点经度">
          <el-input v-model="updateOrderForm.startlatitude" placeholder="请输入起点经度" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="起点纬度">
          <el-input v-model="updateOrderForm.startlongitude" placeholder="请输入起点纬度" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="终点经度">
          <el-input v-model="updateOrderForm.endlatitude" placeholder="请输入终点经度" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="终点纬度">
          <el-input v-model="updateOrderForm.endlongitude" placeholder="请输入终点纬度" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="骑行距离">
          <el-input v-model="updateOrderForm.distance" placeholder="请输入骑行距离" style="width: 220px;" />
        </el-form-item>
        <el-form-item label="生成时间">
          <el-date-picker type="datetime" v-model="updateOrderForm.createdat" placeholder="请选择选择订单生成时间" value-format="YYYY-MM-DD HH:mm:ss" @change="selectChange" />
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="dialogUpdateVisible = false">取 消</el-button>
          <el-button type="primary" @click="UpdateOrder">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { getBikeList, putBike } from '../../api/bike';
import { putOrder } from '../../api/order';
import { deleteOrderById } from '../../api/order';
import { addOrder } from '../../api/order';
import { getOrderList } from '../../api/order';
import { listUsers } from '../../api/users';

export default {
  name: 'bikes',
  data() {
    return {
      tableData: [],
      orderTableData: [],
      pageSize: 5,
      pageNum: 1,
      status: '',
      options: [
        { value: '1', label: '可使用单车' },
        { value: '0', label: '不可使用单车' }
      ],
      total: 0,
      dialogFormVisible: false,
      dialogUpdateVisible: false,
      Bikenumber: '',
      UserId: '', // 根据用户ID搜索
      updateOrderForm: {
        orderid: '',
        bikeid: '',
        userid: '',
        starttime: '',
        endtime: '',
        startlatitude: '',
        startlongitude: '',
        endlatitude: '',
        endlongitude: '',
        distance: '',
        createdat: '',
        note: ''
      },
      bikeForm: {
        id: '',
        bikenumber: 'Tom',
        createat: '2024-12-27 20:32:29',
        lastuseat: '2024-12-26 00:00:00',
        latitude: '106',
        longitude: '210',
        batterylevel: '50',
        status: '1'
      },
      addBike: {
        bikenumber: 'Tom',
        createat: '2024-12-27 20:32:29',
        lastuseat: '2024-12-26 00:00:00',
        latitude: '106',
        longitude: '210',
        batterylevel: '50',
        status: '1'
      },
      addOrderBike: {
        bikeid: '',
        userid: '',
        starttime: '',
        endtime: '',
        startlatitude: '',
        startlongitude: '',
        endlatitude: '',
        endlongitude: '',
        distance: '',
        createdat: '',
        note: ''
      },
      bikeOptions: [],
      userOptions: []
    };
  },
  created() {
    this.load();
    this.orderLoad();
    this.fetchBikeOptions();
    this.fetchUserOptions();
  },
  methods: {
    // 获取单车选项
    async fetchBikeOptions() {
      try {
        const response = await getBikeList(1, 999, '', '');
        console.log('Response:', response); // 打印完整响应
        console.log('Response Data:', response.data); // 打印响应的 data 部分
        // 确保 response.data 和 response.data.bikes 存在
        if (response.data && response.data.records) {
          // 只提取单车的 id
          this.bikeOptions = response.data.records.map(bike => ({
            value: bike.id, // 使用 bike.id 作为选项的值
            label: bike.bikenumber // 使用 bike.bikeNumber 作为选项的标签
          }));
        } else {
          console.error('Unexpected response structure', response);
        }
      } catch (error) {
        console.error('获取单车数据失败', error);
      }
    },

    // 获取用户选项
    async fetchUserOptions() {
      try {
        const response = await listUsers({ pageNum: 1, pageSize: 999, status: '', username: '' });
        console.log('Response:', response); // 打印完整响应
        console.log('Response Data:', response.data); // 打印响应的 data 部分
        // 确保 response.data 和 response.data.user 存在
        if (response.data && response.data.user) {
          this.userOptions = response.data.user.map(user => ({
            value: user.userId, // 使用 userId 作为选项的值
            label: user.username  // 使用 userId 作为选项的标签
          }));
        } else {
          console.error('Unexpected response structure', response);
        }
      } catch (error) {
        console.error('获取用户数据失败', error);
      }
    },

    // 加载单车列表
    load() {
      getBikeList(this.pageNum, this.pageSize, this.Bikenumber, this.status).then(res => {
        console.log(res);
        if (res.code === 200) {
          // 提取单车数据
          this.tableData = res.data.records.map(bike => ({
            id: bike.id,
            bikeNumber: bike.bikeNumber,
            createdAt: bike.createdAt,
            lastUsedAt: bike.lastUsedAt,
            latitude: bike.latitude,
            longitude: bike.longitude,
            batteryLevel: bike.batteryLevel,
            status: bike.status
          }));
          this.total = res.data.total;
        } else {
          this.$message.warning(res.msg);
        }
      });
    },

    // 加载订单列表
    orderLoad() {
      getOrderList(this.pageNum, this.pageSize, this.UserId).then(res => {
        if (res.code === 200) {
          this.orderTableData = res.data.records;
          this.total = res.data.total;
        }
      });
    },

    // 增加订单
    addBikeOrder() {
      addOrder(this.addOrderBike).then(res => {
        if (res.code === 200) {
          this.$message.success("增加成功");
          this.orderLoad();
          this.dialogFormVisible = false;
        }
      });
    },

    // 删除订单
    deleteOrder(id) {
      this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteOrderById(id).then(res => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.orderLoad();
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 更新订单表单
    updateOrder(Order) {
      this.dialogUpdateVisible = true;
      this.updateOrderForm.orderid = Order.orderid;
      this.updateOrderForm.userid = Order.userid;
      this.updateOrderForm.bikeid = Order.bikeid;
      this.updateOrderForm.starttime = Order.starttime;
      this.updateOrderForm.endtime = Order.endtime;
      this.updateOrderForm.startlatitude = Order.startlatitude;
      this.updateOrderForm.startlongitude = Order.startlongitude;
      this.updateOrderForm.endlatitude = Order.endlatitude;
      this.updateOrderForm.endlongitude = Order.endlongitude;
      this.updateOrderForm.distance = Order.distance;
      this.updateOrderForm.createdat = Order.createdat;
    },

    // 提交更新订单
    UpdateOrder() {
      this.dialogUpdateVisible = false;
      putOrder(this.updateOrderForm).then(res => {
        if (res.code === 200) {
          this.$message.success("更新成功");
          this.orderLoad();
        }
      });
    },

    // 分页处理
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.load();
    },

    // 重置搜索条件
    reset() {
      this.status = '';
      this.Bikenumber = '';
      this.load();
    }
  }
};
</script>

<style scoped>
.bikes-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page {
  display: flex;
  margin-top: 10px;
  justify-content: end;
}

.block {
  display: flex;
  justify-content: end;
}
</style>